package com.tuzhi.filestore.fileback;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.tuzhi.filestore.config.FileStoreConfig;
import com.tuzhi.util.DateTzUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 文件备份服务类
 */
@Service
@Slf4j
public class FileBackupsServiceImpl {
    //备份文件指定日期（30天前的）
    final static int day = 90;
    final static long day_ms = 24 * 60 * 60 * 1000;
    @Autowired
    FileStoreConfig fileStoreConfig;


    /**
     * 加载今天之前  beforeTday 天的文件集合记录
     *
     * @param beforeTday
     * @return
     */
    private List<File> loadFilesOfThenDay(String dir, int beforeTday) {
        List<File> fileList = new ArrayList<>();
        File directory = new File(dir);
        File[] files = directory.listFiles();
        long sevenDaysAgo = new Date().getTime() - beforeTday * day_ms;
        if (ArrayUtils.isNotEmpty(files)) {
            for (File file : files) {
                if (file.isFile() && file.lastModified() < sevenDaysAgo) {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }


    public void backupsFile() {
        String dirName = DateUtil.format(new Date(), "yyyyMMdd");
        String backPathDir = Paths.get(fileStoreConfig.getSaveLogPath(), "backups", dirName).toString();
        if (FileUtil.exist(backPathDir)) {
            log.info("目录己存在：不备份:{}", dirName);
            return;
        }
        //待备份的目录
        String srcDir = Paths.get(fileStoreConfig.getSavePath(), "tuovisual").toString();
        List<File> files = loadFilesOfThenDay(srcDir, day);
        //1.copy文件到指定的目录
        files.forEach(f -> {
            String paths = Paths.get(backPathDir, f.getName()).toString();
            File newFile = new File(paths);
            FileUtil.move(f, newFile, true);
        });
        log.info("{}:备份文件数量：{}", backPathDir, files.size());
    }


    /**
     * 备份客户上传的模型文件
     */
    private void backupsFileOfUpModelFile() {
        Date curDate = new Date();
        Date srcDate = DateTzUtil.addDays(curDate, -1 * day);
        String srcDirName = DateUtil.format(srcDate, "yyyyMM");
        //待备份的目录
        String srcDir = Paths.get(fileStoreConfig.getSavePath(), srcDirName).toString();
        List<File> files = loadFilesOfThenDay(srcDir, day);
        String dirName = DateUtil.format(new Date(), "yyyyMMdd");
        String backPathDir = Paths.get(fileStoreConfig.getSaveLogPath(), "backupsModel", dirName).toString();
        //1.copy文件到指定的目录
        files.forEach(f -> {
            String paths = Paths.get(backPathDir, f.getName()).toString();
            File newFile = new File(paths);
            FileUtil.move(f, newFile, true);
        });
        log.info("{}:备份文件数量：{}", backPathDir, files.size());
    }

    /**
     * 备份模型文件，与解释后的bin文件
     */
    public void backFile() {
        backupsFileOfUpModelFile();
        backupsFile();
    }

    /**
     * 清除备份目录
     */
    public void clearBackDir() {
        String dirPath = fileStoreConfig.getSaveLogPath();
        String backPathDir = Paths.get(dirPath, "backupsModel").toString();
        FileUtil.del(backPathDir);
        backPathDir = Paths.get(dirPath, "backups").toString();
        FileUtil.del(backPathDir);
    }

    /**
     * 清除超过 beforeTday 天的文件集合记录
     */
    public void clearTimeLimitFile() {
        //1.清除客户上传的模型文件
        Date curDate = new Date();
        Date srcDate = DateTzUtil.addDays(curDate, -1 * day);
        String srcDirName = DateUtil.format(srcDate, "yyyyMM");
        //待删除过期文件的目录
        String srcDir = Paths.get(fileStoreConfig.getSavePath(), srcDirName).toString();
        List<File> files = loadFilesOfThenDay(srcDir, day);
        files.forEach(f -> {
            FileUtil.del(f);
        });
        log.info("{}:清除客户上传的模型文件：{}", srcDir, files.size());
        //2.删除解释后的bin过期文件
        srcDir = Paths.get(fileStoreConfig.getSavePath(), "tuovisual").toString();
        files = loadFilesOfThenDay(srcDir, day);
        files.forEach(f -> {
            FileUtil.del(f);
        });
        log.info("{}:删除解释后的bin过期文件：{}", srcDir, files.size());
    }

}
